package com.glela.serial.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.util.DateUtil;
import com.glela.constant.BizConstant;
import com.glela.goods.model.vo.goods.GoodsSimpleVo;
import com.glela.goods.model.vo.goods.SimpleGoods;
import com.glela.goods.service.GoodsService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.UserFansMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.User;
import com.glela.platform.model.VisitorClickRecord;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.serial.mapper.JiangshiSerialContentMapper;
import com.glela.serial.mapper.JiangshiSerialGoodsMapper;
import com.glela.serial.mapper.JiangshiSerialMapper;
import com.glela.serial.model.JiangshiSerial;
import com.glela.serial.model.JiangshiSerialContent;
import com.glela.serial.model.response.ResponseSerialContent;
import com.glela.serial.model.response.ResponseSerialDetail;
import com.glela.serial.service.JiangshiSerialService;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

/**
 * 校妆APP讲师专区ServiceImpl
 * 
 * @author 卫耀华
 *
 */
@Service("jiangshiSerialService")
public class JiangshiSerialServiceImpl implements JiangshiSerialService {

	private static Logger logger = LoggerFactory.getLogger(JiangshiSerialServiceImpl.class);

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private JiangshiSerialMapper jiangshiSerialMapper;
	@Autowired
	private JiangshiSerialGoodsMapper jiangshiSerialGoodsMapper;
	@Autowired
	private JiangshiSerialContentMapper jiangshiSerialContentMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private UserFansMapper userFansMapper;

	@Override
	public ResponseEntity<?> getTeacherSerial(long userId, long talentId) {
		logger.info("---begin---getTeacherSerial---Impl---");
		// 获取用户信息
		int roleId = 0;
		if (userId > 0) {
			User user = userMapper.selectByPrimaryKey(userId);
			if (user != null) {
				roleId = user.getRoleId();
			}
		}
		// 获取店主信息
		User teacher = userMapper.selectByPrimaryKey(talentId);
		if (teacher == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
		}
		// 获取一条有效的讲师期资讯信息
		JiangshiSerial serial = jiangshiSerialMapper.selectOne();
		if (serial == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20137), HttpStatus.OK);
		}
		Map<String, Object> map = new HashMap<String, Object>();
		// 拼装讲师信息
		map.put("talentId", teacher.getId());// 讲师ID
		map.put("talentRoleId", teacher.getRoleId());// 店主角色ID
		map.put("talentHeadPhoto", StringUtils.isEmpty(teacher.getPicture()) ? "" : teacher.getPicture());// 讲师头像
		map.put("talentNickName", StringUtils.isEmpty(teacher.getNickName()) ? "" : teacher.getNickName());// 讲师昵称
		//在粉丝表中验证大人和用户的关系
		int isFans = userFansMapper.selectUserFansByUserIdAndTalentID(talentId, userId);
		if (isFans > 0) {
			isFans = BizConstant.ENJOY_TYPE_Y;
		}
		map.put("isEnjoy", isFans);//是否有关注
		map.put("backgroundImage", teacher.getBackgroundImage());// 讲师背景图
		map.put("fansCount", teacher.getFansCount());// 粉丝数
		map.put("personDescription", StringUtils.isEmpty(teacher.getSynopsis()) ? "" : teacher.getSynopsis());// 达人个人简介
		// 拼装期资讯信息
		map.put("serialId", serial.getId());// 期ID
		map.put("seeCount", serial.getSeeCount());// 浏览数
		map.put("title", serial.getTitle());// 标题
		map.put("coverImgpath", serial.getCoverImgpath());// 封面图
		List<GoodsSimpleVo> list = new ArrayList<GoodsSimpleVo>();
		// 查询期资讯下的B区正常商品集合
		List<SimpleGoods> simpleList = jiangshiSerialGoodsMapper.selectGoodsBySerialId(serial.getId());
		if (simpleList != null && simpleList.size() > 0) {
			list = goodsService.simpleGoodsTrans(simpleList, 0, roleId);
		}
		map.put("goodsList", list);// 期商品
		map.put("goodsNum", list.size());// 商品数量
		// 访问信息存到缓存中
		saveVisitInfoToRedis(userId, talentId);
		return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
	}

	@Override
	public ResponseSerialDetail getDetailBySerialId(int roleId, long shareUserId, int serialId) {
		logger.info("---begin---B店期详情---impl---");
		//查询讲师期资讯
		JiangshiSerial serial = jiangshiSerialMapper.selectById(serialId);
		if (serial == null) {
			return null;
		}
		int shareRoleId = 0;//分享者角色
		User shareUser = userMapper.selectByPrimaryKey(shareUserId);
		if (shareUser != null) {
			shareRoleId = shareUser.getRoleId();
		}
		ResponseSerialDetail detail = new ResponseSerialDetail();//期详情VO 用于返回前端
		//查询期资讯下的b区正常商品
		List<SimpleGoods> simpleList = jiangshiSerialGoodsMapper.selectGoodsBySerialId(serial.getId());
		//设置商品价格
		List<GoodsSimpleVo> list = goodsService.simpleGoodsTrans(simpleList, shareRoleId, roleId);
		//封装detail信息
		detail.setGoodsList(list);
		detail.setSerialId(serial.getId());
		detail.setTitle(serial.getTitle());
		detail.setCoverImgpath(serial.getCoverImgpath());
		// 期下面的图片列表
		List<JiangshiSerialContent> scList = jiangshiSerialContentMapper.selectContentsBySerialId(serialId);
		List<ResponseSerialContent> rscList = new ArrayList<ResponseSerialContent>();
		if (scList != null && scList.size() > 0) {
			for (JiangshiSerialContent sc : scList) {
				ResponseSerialContent rsc = new ResponseSerialContent();
				BeanUtils.copyProperties(sc, rsc);
				rsc.setSerialContentId(sc.getId());
				rsc.setSerialId(serial.getId());
				rscList.add(rsc);
			}
		}
		// 添加图片列表
		detail.setSerialContentImages(rscList);
		//期资讯浏览数+1
		jiangshiSerialMapper.updateSeeCount(serialId);
		return detail;
	}

	protected void saveVisitInfoToRedis(long userId, long talentId) {
		VisitorClickRecord record = new VisitorClickRecord();
		record.setUserId(userId);
		record.setTalentId(talentId);
		record.setVistTime(DateUtil.currentStringDate());// 服务器的当前时间
		Jedis jedis = null;
		try {
			jedis = redisUtil.getJedis();
			Pipeline pipeline = jedis.pipelined();
			redisUtil.expire(RedisKeys.VISTOR_RECORED, 46800);// 失效时间13小时
			String json = JSON.toJSONString(record);
			redisUtil.sadd(RedisKeys.VISTOR_RECORED, json);
			pipeline.sync();
		} catch (Exception e) {
			logger.error("访客记录到redis时发生异常:", e);
		} finally {
			if (jedis != null) {
				redisUtil.returnJedis(jedis);
			}
		}
	}
}
